<template>
	<div id="dataManage" class="dataManage">
		<input class="fileInput" id="upload" type="file" @change="importExcel($event.target)"  accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
		<x-button mini :gradients="['#FF2719', '#FF61AD']" class="fileImport" @click.native="importData">开始导入</x-button>
		<div v-transfer-dom>
			<confirm v-model="show"
			         :title="confirmTitle"
			         @on-cancel="onCancel"
			         @on-confirm="onConfirm">
				<p style="text-align:center;"><span v-html="message"></span></p>
			</confirm>
		</div>
		<div v-transfer-dom>
			<alert v-model="showFinish" :title="finishTitle" @on-show="onShow" @on-hide="onHide"> {{finishMessage}} </alert>
		</div>
		<div v-transfer-dom>
			<loading :show="showLoading" text=""></loading>
		</div>
		<grid class="gridTitle" :show-vertical-dividers="false">
			<grid-item>
				<span class="grid-center">姓名</span>
			</grid-item>
			<grid-item>
				<span class="grid-center">电话</span>
			</grid-item>
			<grid-item>
				<span class="grid-center">性别</span>
			</grid-item>
			<grid-item>
				<span class="grid-center">生日</span>
			</grid-item>
			<grid-item>
				<span class="grid-center">操作</span>
			</grid-item>
		</grid>
		<grid class="gridCell" v-for="(item, index) in data" :show-vertical-dividers="false">
			<grid-item class="grid-item" @click.native="jumpTo(data.id)">
				<span class="grid-center-link" v-if="item.name != null">{{item.name}}</span>
				<span class="grid-center-link" v-else>未填</span>
			</grid-item>
			<grid-item class="grid-item">
				<span class="grid-center-link" v-if="item.phone != null">{{item.phone}}</span>
				<span class="grid-center-link" v-else>未填</span>
			</grid-item>
			<grid-item class="grid-item">
				<span class="grid-center-link" v-if="item.sex == 1">男</span>
				<span class="grid-center-link" v-else-if="item.sex == 0">女</span>
				<span class="grid-center-link" v-else>未填</span>
			</grid-item>
			<grid-item class="grid-item">
				<span class="grid-center-link" v-if="item.birthday != null">{{item.birthday}}</span>
				<span class="grid-center-link" v-else>未填</span>
			</grid-item>
			<grid-item class="grid-item" @click.native="onClickDelete(index, item)">
				<span class="grid-center-link"><x-icon type="ios-close-outline" size="13"></x-icon></span>
			</grid-item>
		</grid>
	</div>
</template>

<script>
	import dateutils from '@/utils/date'
	import XLSX from 'xlsx'
	import bus from '@/event/eventBus'
	import NetWorking from '../../../utils/networking'
	import {Loading, Alert, Cell, XButton, Group, GridItem, Grid, TransferDomDirective as TransferDom, Confirm, Checker, CheckerItem} from 'vux'
	export default {
		name: "data-manage",
		components: {
			Loading,
			Alert,
			Cell,
			XButton,
			Group,
			GridItem,
			Grid,
			TransferDom,
			Confirm,
			Checker,
			CheckerItem
		},
		directives: {
			TransferDom
		},
		data() {
			return {
				showLoading: false,
				showFinish: false,
				finishTitle: '提示',
				finishMessage: '数据导入成功',
				importFlag: false,
				items: [],
				data: [],
				message: '',
				title: '数据导入',
				confirmTitle: '操作提示',
				show: false,
				curIndex: '',
				curItem: ''
			}
		},
		created: function () {
			bus.$emit("barController", 1)
			bus.$emit("setTopSimpleTitle", this.title)
		},
		methods: {
			onShow() {
			},
			onHide() {
				if(this.importFlag == true){
					this.$router.replace('marketingList')
				}
			},
			importData() {
				if(this.data.length == 0){
					this.finishMessage = '请选择正确的数据文件'
					this.showFinish = true
					return
				}
				this.showLoading = true
				let _this = this
				NetWorking.doPost(
					'customers/importMembers',
					null,
					{
						customerListStr: JSON.stringify(this.data)
					},
					null
				).then(
					response => {
						let rs = response.data
						if(rs.error_code == 0){
							_this.finishMessage = '数据导入成功'
							_this.showFinish = true
							_this.importFlag = true
							_this.showLoading = false
						}else{
							_this.showLoading = false
							alert(rs.error_message)
						}
					}
				)
			},
			importExcel(fileHandler) {
				let _this = this
				let file = fileHandler.files[0] // 使用传统的input方法需要加上这一步
				const types = file.name.split('.')[1]
				const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
				if (!fileType) {
					alert('格式错误！请重新选择')
					return
				}
				this.file2Xce(file).then(tabJson => {
					if (tabJson && tabJson.length > 0) {
						let tableHeader = Object.keys(tabJson[0]);
						let tableTbody = tabJson;
						for(let i=0; i < tabJson.length; i++){
							for(let j=0; j < tabJson[i].sheet.length; j++){
								_this.items.push(tabJson[i].sheet[j])
								let sex = null
								if(tabJson[i].sheet[j].性别 == '男'){
									sex = 1
								}else if(tabJson[i].sheet[j].性别 == '女'){
									sex = 0
								}
								let birthday = null
								if(tabJson[i].sheet[j].生日 != null){
									birthday = dateutils.getYYMMDD(new Date(tabJson[i].sheet[j].生日))
									//birthday = new Date(tabJson[i].sheet[j].生日)
								}
								_this.data.push({name: tabJson[i].sheet[j].姓名, phone: tabJson[i].sheet[j].电话, sex: sex, birthday: birthday})
							}
							//_this.items.concat(tabJson[i].sheet)
						}
						//this.xlsxJson = tabJson
						// xlsxJson就是解析出来的json数据,数据格式如下
						// [
						//   {
						//     sheetName: sheet1
						//     sheet: sheetData
						//   }
						// ]
					}
				})
			},
			file2Xce(file) {
				return new Promise(function(resolve, reject) {
					const reader = new FileReader()
					reader.onload = function(e) {
						const data = e.target.result
						this.wb = XLSX.read(data, {
							type: 'binary',
							cellDates: true
						})
						const result = []
						this.wb.SheetNames.forEach((sheetName) => {
							result.push({
								sheetName: sheetName,
								sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
							})
						})
						resolve(result)
					}
					//reader.readAsBinaryString(file.raw)
					reader.readAsBinaryString(file) // 传统input方法
				})
			},
			onCancel: function () {
				this.show = false
			},
			onConfirm: function () {
				this.deleteElement()
			},
			onClickDelete(index, item) {
				this.show = true
				this.curIndex = index
				this.curItem = item
				this.message = '确定要删除<span style="color: red; font-weight: bold">' + this.curItem.name + '</span>吗？'
			},
			jumpTo(id) {
				this.$router.push({ name: "roleUpdate", params: {id: id}})
			},
			deleteElement () {
				this.data.splice(this.curIndex, 1)
			}
		}
	}
</script>

<style>
	.dataManage {
		margin-top: 46px;
		margin-bottom: 80px;
	}

	.fileInput {
		background: orange;
		margin-bottom: 10px;
		margin-top: 10px;
		color: white;
		width: 150px;
		margin-left: 5px;
	}

	.fileImportCheck {
		border: 1px solid #ececec;
		padding: 0px 5px;
		background-color: white;
		margin-right: 5px;
		font-size: 13px;
		margin-bottom: 10px;
	}
	.fileImportCheckSelected {
		background: #ffffff url(../../../assets/img/icon_check.png) no-repeat right bottom;
		border-color: #ff4a00;
	}

	.fileImport {
		margin-top: 10px;
		margin-right: 10px !important;
		padding: 2px 10px !important;
		font-size: 13px !important;
		line-height: initial !important;
	}
</style>